'use strict';

const app = require('../../app');
const Server = require('../../server');
const Toast = require('../toast');
const TopMenu = require('../top_menu');
const create = require('../../create');

module.exports = () => {

  // shared
  $('#shared').mouseup(function () {
    $(this).select();
  });

  $('#btn_share').on('click', (e) => {
    e.stopPropagation();
    const $icon = $(this).find('.fa-share');
    $icon.addClass('fa-spin fa-spin-faster');

    const $shareForm = $('#share-form');
    $shareForm.show();

    // 点其他地方时关闭
    $(document).on('click.shareFormHide', () => {
      const $form = $('#share-form');
      const $button = $('#btn_share');
      // 如果点击的是弹窗或按钮本身，不关闭
      if ($form.is(event.target) || $form.has(event.target).length > 0 ||
        $button.is(event.target) || $button.has(event.target).length > 0) {
        return;
      }
      $shareForm.hide();
      $(document).off('click.shareFormHide');
    });


    $('#btn_submit_share').on('click', (e) => {
      const select = $("#share-category");
      const category = select.val();
      const categoryName = $('#share-category option:selected').text();
      const name = $("#share-eng-name").val();
      const algorithmName = $("#share-name").val();
      Server.shareScratchPaper(category, categoryName, name, algorithmName);
      $shareForm.hide();
    });
  });

  $('#btn_save').click(function () {
    Server.tempSaveScratchPaper();
  });


  $('#btn_online').click(function () {
    if(confirm("确定要上线吗")) {
      Server.onlineAlgorithm();
    }
  });

  $('#btn_refuse').click(function () {
    if(confirm("确定要拒绝上线吗")) {
      Server.refuseAlgorithm();
    }
  });

  // control

  const $btnRun = $('#btn_run');
  const $btnTrace = $('#btn_trace');
  const $btnPause = $('#btn_pause');
  const $btnPrev = $('#btn_prev');
  const $btnNext = $('#btn_next');
  const $btnGenerate = $('#btn_generate');

  // initially, control buttons are disabled
  TopMenu.disableFlowControl();

  $btnRun.click(() => {
    $btnTrace.click();
    $btnPause.removeClass('active');
    $btnRun.addClass('active');
    TopMenu.enableFlowControl();
    var err = app.getEditor().execute();
    if (err) {
      console.error(err);
      Toast.showErrorToast(err);
      TopMenu.resetTopMenuButtons();
    }
  });

  $btnPause.click(() => {
    $btnRun.toggleClass('active');
    $btnPause.toggleClass('active');
    if (app.getTracerManager().isPause()) {
      app.getTracerManager().resumeStep();
    } else {
      app.getTracerManager().pauseStep();
    }
  });

  $btnPrev.click(() => {
    $btnRun.removeClass('active');
    $btnPause.addClass('active');
    app.getTracerManager().pauseStep();
    app.getTracerManager().prevStep();
  });

  $btnNext.click(() => {
    $btnRun.removeClass('active');
    $btnPause.addClass('active');
    app.getTracerManager().pauseStep();
    app.getTracerManager().nextStep();
  });

  $btnGenerate.click(() => {
     create.init();
  });

};
